/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package skeleton;

import java.util.*;
/**
 *
 * @author Arch
 */
public class Logger {
    private static Stack lastCalled = new Stack();
    private static boolean on = true;

    public static void Enter(String functionName) throws Exception
    {
        if (functionName.isEmpty())
        {
            throw new Exception("LogFunctionLeave: empty function name");
        }
        if (on)
        {
            PrintFunction("Enter " + functionName);
        }
        lastCalled.push(functionName.substring(0, (functionName.indexOf(" ")== -1) ? functionName.length() : functionName.indexOf(" ") ));
    }
 
    public static void Leave(String functionName) throws Exception
    {
        //check for too many leaves
        try {
            lastCalled.peek();
        } catch (EmptyStackException emp)
        {
            throw new Exception("LogFunctionLeave: empty call stack nowhere to leave from, caller is: " + functionName);
        }
        
        //check for corrent leave
        if (!functionName.equals((String)lastCalled.peek())) {
            
            throw new Exception("LogFunctionLeave: cross leave, caller is: " + functionName + " should be: " + lastCalled.peek());
        }
        lastCalled.pop();
        if (on)
        {
            PrintFunction("Leave " + functionName);
        }
    }

    private static void PrintFunction(String functionName)
    {
        for (int i = 0; i < lastCalled.size(); i++) {
            System.out.print("\t");
        }
        System.out.print(functionName + "\n");
    }

    public static void PrintCallStack()
    {
        if (!lastCalled.isEmpty())
        {
            System.out.println("Call stack");
        }
        else {
            System.out.println("Call stack is empty");
        }
        while (!lastCalled.isEmpty())
        {
            PrintFunction((String)lastCalled.pop());
        }
    }

    public static void Message(String msg)
    {
        if (on)
        {
            PrintFunction(msg);
        }
    }

    public static void ON()
    {
        on = true;
        System.out.println("Logger is now ON");
    }
    
    public static void OFF()
    {
        on = false;
        System.out.println("Logger is now OFF");
    }

}
